<template>
  <div class="table-pagination">
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[8, 16, 24, 32]"
      :total="total"
      :layout="layout"
      :teleported="false"
      popper-class="pagination-select-dropdown"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script setup lang="ts">
import { watch, computed } from 'vue'

interface Props {
  total: number
  layout?: string
  pageSize?: number
  currentPage?: number
}

interface Emits {
  (e: 'update:pageSize', value: number): void
  (e: 'update:currentPage', value: number): void
  (e: 'size-change', value: number): void
  (e: 'current-change', value: number): void
}

const props = withDefaults(defineProps<Props>(), {
  layout: 'total, sizes, prev, pager, next',
  pageSize: 8,
  currentPage: 1,
})

const emit = defineEmits<Emits>()

const pageSize = computed({
  get: () => props.pageSize,
  set: (value) => emit('update:pageSize', value),
})

const currentPage = computed({
  get: () => props.currentPage,
  set: (value) => emit('update:currentPage', value),
})

// 监听分页变化
watch(
  [currentPage, pageSize],
  ([newPage, newSize]) => {
    emit('size-change', newSize)
    emit('current-change', newPage)
  },
  { deep: true },
)

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
}
</script>

<style scoped lang="scss">
.table-pagination {
  padding: 10px 16px;
  display: flex;
  justify-content: flex-end;
  background-color: var(--el-bg-color);

  :deep(.el-pagination) {
    justify-content: flex-end;
    padding: 0;
    margin: 0;
    font-size: 13px;

    .el-pagination__sizes {
      margin-right: 8px;
    }
  }
}
/* 新增全局样式（注意需要穿透scoped限制） */
:deep(.pagination-select-dropdown) {
  /* 强制弹窗向上展开 */
  top: auto !important;
  bottom: 200%;
  margin-bottom: 4px; /* 添加与分页器的间距 */

  /* 调整箭头方向 */
  .el-popper__arrow {
    top: 100%;
    bottom: auto;
    transform: translateY(-50%) rotate(180deg);
  }
}
</style>
